package com.example.imageview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView ivPhoto;
    private final int[] imgIds = new int[]{ R.drawable.image1, R.drawable.image2,
            R.drawable.image3, R.drawable.image4};
    private int currentIndex = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取ImageView、Button对象
        ivPhoto = findViewById(R.id.iv_pic);
        Button btnPrevious = findViewById(R.id.btn_previous);
        Button btnNext = findViewById(R.id.btn_next);
        // 设置按钮的监听器
        btnPrevious.setOnClickListener(this);
        btnNext.setOnClickListener(this);
    }

    /**
     * Google官方认为：if方式在UI中几乎不损失性能，不再推荐switch...case
     * @param view
     */
    @Override
    public void onClick(View view) {
        final int id = view.getId();
        if (id == R.id.btn_previous) {
            currentIndex--;
            if(currentIndex < 0) {
                currentIndex = imgIds.length - 1;
            }
        } else if(id==R.id.btn_next) {
            currentIndex++;
            if(currentIndex == imgIds.length) {
                currentIndex = 0;
            }
        }
        ivPhoto.setImageResource(imgIds[currentIndex]);
    }
}